package switchviz.graphic.gauge.bargraph.scale;

import java.util.StringTokenizer;

import org.jdom.Element;


public class BarGraphScalePersistence 
{
	private static final String GRIDCOLOR = "gridcolor";
	private static final String COORDINATECOLOR = "coordinatecolor";
	private static final String NUMGRIDLINES = "numgridlines";
	
	private Element _root = null;
	private BarGraphScaleDataModel _datamodel = null;
	
	public BarGraphScalePersistence(Element root)
	{
		_root = root;
	}
	
	public BarGraphScaleDataModel getDataModelFromElement()
	{
		if(_root.getChild(NUMGRIDLINES) != null)
			getDataModel().setNumgridlines(Integer.valueOf(_root.getChildText(NUMGRIDLINES)));
		if(_root.getChild(GRIDCOLOR) != null)
			getDataModel().setGridcolor(getColorCode(_root.getChildText(GRIDCOLOR)));
		if(_root.getChild(COORDINATECOLOR) != null)
			getDataModel().setCoordinatecolor(getColorCode(_root.getChildText(COORDINATECOLOR)));
		return getDataModel();
	}
	
	public Element setDataModel(BarGraphScaleDataModel datamodel)
	{
		_datamodel = datamodel;
		return saveDataModel();
	}
	
	private void addNode(String nodename, String value)
	{
		if(_root.getChild(nodename) != null)
			_root.getChild(nodename).setText(value);
		else
			_root.addContent(new Element(nodename).setText(value));
	}
	
	private float[] getColorCode(String colorcode)
	{
		float[] color = {0.0f, 0.0f, 0.0f};
		StringTokenizer tokenizer = new StringTokenizer(colorcode, ";", false);
		int i = 0;
		while(tokenizer.hasMoreTokens())
		{
			if(i == 3) break;
			color[i] = Float.valueOf(tokenizer.nextToken());
			++i;
		}
		return color;
	}
	
	private BarGraphScaleDataModel getDataModel()
	{
		if(_datamodel == null)
			_datamodel = new BarGraphScaleDataModel();
		return _datamodel;
	}
	
	private Element saveDataModel()
	{
		addNode(NUMGRIDLINES, String.valueOf(getDataModel().getNumgridlines()));
		String colorcode = getDataModel().getGridcolor()[0] + ";" + getDataModel().getGridcolor()[1] + ";" + getDataModel().getGridcolor()[2];
		addNode(GRIDCOLOR, colorcode);
		colorcode = getDataModel().getCoordinatecolor()[0] + ";" + getDataModel().getCoordinatecolor()[1] + ";" + getDataModel().getCoordinatecolor()[2];
		addNode(COORDINATECOLOR, colorcode);
		return _root;
	}
}
